<template>
    <div class="bulletScreen">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="弹幕样式" name="bulletScreenStyle">
                <iframe id="iframeBtsSetting" src="https://www.office2.cn/staticft/bulletScreenSetting/index.html" frameborder="0"></iframe>
            </el-tab-pane>
            <el-tab-pane label="快捷语" name="quickLanguage">
                <el-row>
                    <el-button type="primary" plain round> 导入 </el-button>
                    <el-button type="primary" plain round> 导出 </el-button>
                </el-row>
                <el-row class="quickLanguage-list">
                    <el-row v-for="(item, index) in bulletScreen.quickLanguageList" :key="index" style="line-height:32px;">
                        <el-col :span="1">{{index + 1}}：</el-col>
                        <el-col :span="10">
                            <el-input placeholder="请输入内容" v-model="item.value" clearable></el-input>
                        </el-col>
                        <el-col :span="4" :offset="1">
                            <i class="el-icon-circle-plus-outline" @click="addQuickLanguage(index)"></i>
                            <i class="el-icon-remove-outline" @click="delQuickLanguage(index)"></i>
                        </el-col>
                    </el-row>
                </el-row>
            </el-tab-pane>
            <el-tab-pane label="VIP管理" name="vipManage">
                <el-row class="vipManage-query">
                    <el-form :inline="true" :model="vipManageQuery">
                        <el-form-item label="昵称：">
                            <el-input v-model="vipManageQuery.nickName" placeholder="昵称"></el-input>
                        </el-form-item>
                        <el-form-item label="加入时间：">
                            <el-date-picker
                                v-model="vipManageQuery.dateTime"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :picker-options="vipManageQuery.dateTimePickOps"
                            >
                            </el-date-picker>
                            <el-button type="primary" icon="el-icon-search" round @click="vipSearch()" style="margin-left:20px;">查询</el-button>
                        </el-form-item>
                        <el-form-item style="float:right;">
                            <el-button type="primary" round @click="showDialogVipAdd()">添加VIP用户</el-button>
                            <el-button type="danger" round @click="vipBatchOut()">批量移出VIP</el-button>
                        </el-form-item>
                    </el-form>
                </el-row>
                <el-row class="vipManage-list">
                    <el-row class="vipManage-list-main">
                        <div class="chooseBg">
                            <el-button type="text" @click="vipCheckAll(vipList)">全选</el-button>
                            <el-button type="text" @click="vipCheckInvert(vipList)">反选</el-button>
                        </div>
                        <template>
                            <el-table
                                ref="vipListTable"
                                :data="vipList"
                                border
                                stripe
                                style="width: 100%;"
                                v-loading="vipListTableLoading"
                                element-loading-text="拼命加载中"
                                element-loading-spinner="el-icon-loading"
                                element-loading-background="rgba(0, 0, 0, 0.8)"
                                @selection-change="vipSelectionChange"
                            >
                                <el-table-column
                                    width="100"
                                    type="selection"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="headimgurl"
                                    label="头像"
                                    align="center"
                                >
                                    <template slot-scope="scope">
                                        <el-avatar style="vertical-align:middle;" :src="scope.row.headimgurl"></el-avatar>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="nickname"
                                    label="昵称"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="qdtime"
                                    label="签到时间"
                                    align="center"
                                    :formatter="timeToDate"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="joinviptime"
                                    label="加入VIP时间"
                                    align="center"
                                    :formatter="timeToDate"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    align="center"
                                >
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="vipRemove(scope.row.unionid)">移出VIP</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-row>
                    <el-pagination
                        v-show="vipTotalPage > 1"
                        background
                        layout="prev, pager, next"
                        :total="vipTotalCount"
                        @current-change="vipCurrentChange"
                    >
                    </el-pagination>
                </el-row>
            </el-tab-pane>
        </el-tabs>
        <el-dialog title="添加VIP用户" :visible.sync="dialogVipAddVisible" :close-on-click-modal="false" :close-on-press-escape="false">
            <div class="dialogVipBox">
                <div class="user-search">
                    <el-input
                        placeholder="微信昵称"
                        v-model="userSearchNickname"
                        clearable
                        @input.native="userSearch"
                    >
                    </el-input>
                    <div class="user-search-list"  v-show="userSearchList.length > 0">
                        <el-row class="user-search-list-item" v-for="item in userSearchList" :key="item.unionid">
                            <el-col :span="4">
                                <el-avatar :size="20" :src="item.headimgurl"></el-avatar>
                            </el-col>
                            <el-col :span="16">
                                <span>{{item.nickname}}</span>
                                <span>/</span>
                                <span>{{item.gender === 0 ? '未知' : item.gender === 1 ? '男' : '女'}}</span>
                                <span>/</span>
                                <span>{{item.province}}{{item.city}}</span>
                            </el-col>    
                            <el-col :span="4" style="text-align:center;">
                                <el-button type="text" @click="userSearchChoose(item)">选择</el-button>
                            </el-col>    
                        </el-row>
                    </div>
                </div>
                <div class="user-addVip">
                    <el-col class="user-addVip-item" :span="10" v-for="item in userAddVipList" :key="item.unionid">
                        <el-avatar :size="20" :src="item.headimgurl"></el-avatar>
                        <span>{{item.nickname}}</span>
                        <i class="el-icon-close" @click="userAddVipRemoveItem(item.unionid)" style="color:#D8D8D8;float:right;font-size:20px;margin:5px 0;cursor:pointer;"></i>
                    </el-col>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="userAddVipCancel()">取 消</el-button>
                <el-button type="primary" @click="userAddVipConfirm()">确 定</el-button>
            </div>
        </el-dialog>
        <footerButtons v-show="activeName !== 'vipManage'" @save="saveSetting">
          <div style="float:left;line-height:32px;" slot="left">
            <label >
                弹幕启动开关&nbsp;&nbsp;
                <el-switch v-model="BtsSwitch" @change="BtsSwitchChange()"></el-switch>
            </label>
          </div>
        </footerButtons>
    </div>
</template>

<script>
    import {formatTime} from "@/utils/util";

    export default {
        name: 'barrage',
        data() {
            return{
                activeName: 'bulletScreenStyle',
                bulletScreen: {},
                quickLanguageList: [
                    { value: '看得我尴尬症都犯了' },
                    { value: '地主家的傻儿子' },
                    { value: '前方高能预警，请非战斗人员撤离' }
                ],
                vipManageQuery: {
                    nickName: '',
                    dateTime: '',
                    dateTimePickOps: {
                        shortcuts: [
                            {
                                text: '最近一周',
                                onClick(picker) {
                                    const end = new Date();
                                    const start = new Date();
                                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                    picker.$emit('pick', [start, end]);
                                }
                            },
                            {
                                text: '最近一个月',
                                onClick(picker) {
                                    const end = new Date();
                                    const start = new Date();
                                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                    picker.$emit('pick', [start, end]);
                                }
                            },
                            {
                                text: '最近三个月',
                                onClick(picker) {
                                    const end = new Date();
                                    const start = new Date();
                                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                    picker.$emit('pick', [start, end]);
                                }
                            }
                        ]
                    }
                },
                vipTotalPage: 0,
                vipTotalCount: 0,
                vipPageIndex: 1,
                vipPageSize: 10,
                vipList: [],
                vipListTableLoading: false,
                vipSelection: [],
                dialogVipAddVisible: false,
                userSearchNickname: '',
                userSearchTimer: null,
                userSearchList: [],
                userAddVipList: [],
                sceneId: '',
                BtsSwitch: true,
                defaultBg: null
            }
        },
        created() {
            this.sceneId = this.$route.query.sceneId;

            //获取场景弹幕配置
            this.$api.post(
                '/sceneCfg/findDmSceneCfg',
                {
                    sceneId: this.sceneId,
                },
                res => {
                    this.$message({
                        message: '加载配置成功',
                        type: 'success'
                    });

                    if(res.bulletScreen){
                        this.bulletScreen = JSON.parse(res.bulletScreen);

                        if(!this.bulletScreen.quickLanguageList || this.bulletScreen.quickLanguageList.length == 0){
                            this.bulletScreen.quickLanguageList = this.quickLanguageList;
                        }
                    }

                    if(res.isScreen == '0'){
                        this.BtsSwitch = false;
                    }
                    else if(res.isScreen == '1'){
                        this.BtsSwitch = true;
                    }

                    if(res.defaultBg){
                        this.defaultBg = res.defaultBg;
                    }
                },
                err => {
                    this.$message.error('加载配置失败');
                }
            );

            this.getQueryVIPUserList();
        },
        mounted() {
            let _this = this;

            let frame = document.getElementById('iframeBtsSetting');
            frame.onload = function(){
                frame.contentWindow.postMessage({
                    config: {
                        sceneId: _this.sceneId,
                        bulletScreen: _this.bulletScreen,
                        defaultBg: _this.defaultBg
                    }
                }, '*')

                window.addEventListener('message', function(event){
                    if(event.data.type == 'iframeBtsSetting'){
                        _this.bulletScreen = event.data.config;
                    }
                })
            }
        },
        methods: {
            handleClick(tab, event) {
                // console.log(tab, event);
            },
            addQuickLanguage(index) {
                let item = {
                    value: ''
                }
                this.bulletScreen.quickLanguageList.splice(index + 1, 0, item);
            },
            delQuickLanguage(index) {
                if(this.bulletScreen.quickLanguageList.length <= 3){
                    this.$message({
                        message: '最少含有三条快捷语',
                        type: 'warning'
                    });

                    return;
                }

                this.bulletScreen.quickLanguageList.splice(index, 1);
            },
            vipSearch() {
                this.vipListTableLoading = true;
                //获取vip
                this.$api.post(
                    '/ftUserInfo/queryVIPUserList',
                    {
                        sceneid: this.sceneId,
                        isvip: 1,
                        nickName: this.vipManageQuery.nickName,
                        joinviptime: formatTime(this.vipManageQuery.dateTime[0]),
                        joinvipendtime: formatTime(this.vipManageQuery.dateTime[1]),
                        pageIndex: this.vipPageIndex,
                        pageSize: this.vipPageSize
                    },
                    res => {
                        this.vipListTableLoading = false;

                        this.vipTotalPage = res.totalPage;
                        this.vipTotalCount = res.totalCount;
                        this.vipList = res.result;
                    },
                    err => {
                        this.$message.error('获取vip列表失败');
                    }
                );
            },
            timeToDate(row, column, cellValue) {
                return formatTime(cellValue);
            },
            vipCheckAll(rows) {
                rows.forEach(row => {
                    this.$refs.vipListTable.toggleRowSelection(row, true);
                });
            },
            vipCheckInvert(rows) {
                rows.forEach(row => {
                    this.$refs.vipListTable.toggleRowSelection(row);
                });
            },
            vipSelectionChange(val) {
                this.vipSelection = val;
            },
            vipRemove(unionid) {
                this.$confirm('此操作将移出VIP, 是否继续?', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(() => {
                    this.$api.post(
                        '/ftUserInfo/updateVip',
                        {
                            sceneid: this.sceneId,
                            isvip: 0,
                            unionid: unionid
                        },
                        res => {
                            this.$message({
                                message: '移出VIP成功',
                                type: 'success'
                            });
                            this.getQueryVIPUserList();
                        },
                        err => {
                            this.$message.error('移出VIP失败');
                        }
                    );
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消移出VIP操作'
                    });          
                });
            },
            vipBatchOut() {
                if(this.vipSelection.length == 0){
                    this.$message.error('请选择要移出的VIP');
                    return;
                }

                let unionid = '';
                this.vipSelection.forEach((item, index) => {
                    unionid += item.unionid;
                });
                this.vipRemove(unionid);
            },
            vipCurrentChange(val) {
                this.vipPageIndex = val;

                this.getQueryVIPUserList();
            },
            getQueryVIPUserList() {
                this.vipListTableLoading = true;
                //获取vip
                this.$api.post(
                    '/ftUserInfo/queryVIPUserList',
                    {
                        sceneid: this.sceneId,
                        isvip: 1,
                        pageIndex: this.vipPageIndex,
                        pageSize: this.vipPageSize
                    },
                    res => {
                        this.vipListTableLoading = false;

                        this.vipTotalPage = res.totalPage;
                        this.vipTotalCount = res.totalCount;
                        this.vipList = res.result;
                    },
                    err => {
                        this.$message.error('获取vip列表失败');
                    }
                );
            },
            showDialogVipAdd() {
                this.dialogVipAddVisible = true;
                this.userAddVipList = [];
                this.userSearchList = [];
            },
            userSearch(e) {
                let _this = this;
                clearTimeout(_this.userSearchTimer);
                
                let value = e.target.value;
                _this.userSearchTimer = setTimeout(function(){
                    _this.$api.post(
                        '/ftUserInfo/queryVIPUserList',
                        {
                            sceneid: _this.sceneId,
                            isvip: 0,
                            nickname: value
                        },
                        res => {
                            _this.userSearchList = res.result;
                        },
                        err => {
                            _this.$message.error('查询用户失败');
                        }
                    );
                }, 500);
            },
            userSearchChoose(value) {
                let isHas = false;

                this.userAddVipList.forEach((item, index) => {
                    if(item.unionid == value.unionid){
                        isHas = true;
                    }
                })

                if(!isHas){
                    this.userAddVipList.push(value);
                }
                
                this.userSearchList = [];
            },
            userAddVipRemoveItem(unionid) {
                this.userAddVipList.forEach((item, index) => {
                    if(item.unionid == unionid){
                        this.userAddVipList.splice(index, 1);
                    }
                })
            },
            userAddVipConfirm() {
                let unionid = '';
                this.userAddVipList.forEach((item, index) => {
                    unionid += item.unionid;
                })

                this.$api.post(
                    '/ftUserInfo/updateVip',
                    {
                        sceneid: this.sceneId,
                        isvip: 1,
                        unionid: unionid
                    },
                    res => {
                        this.$message({
                            message: '添加VIP成功',
                            type: 'success'
                        });
                        this.dialogVipAddVisible = false;
                        this.userSearchNickname = '';
                        this.userAddVipList = [];

                        this.getQueryVIPUserList();
                    },
                    err => {
                        this.$message.error('添加VIP失败');
                    }
                );
            },
            userAddVipCancel() {
                this.dialogVipAddVisible = false;
                this.userSearchNickname = '';
                this.userAddVipList = [];
            },
            saveSetting() {
                let quickLanguageList = this.bulletScreen.quickLanguageList;
                let isEmpty = false;
                for(let i = 0; i < quickLanguageList.length; i++){
                    let value = quickLanguageList[i].value;
                    if(value.replace(/\s/g, "") == ''){
                        isEmpty = true;
                        break;
                    }
                }

                if(isEmpty){
                    this.$message.error('快捷语不可为空');
                    return;
                }

                this.$api.post(
                    '/sceneCfg/saveDmSceneCfg',
                    {
                        sceneId: this.sceneId,
                        bulletScreen: this.bulletScreen
                    },
                    res => {
                        this.$message({
                            message: '保存配置成功',
                            type: 'success'
                        });
                    },
                    err => {
                        this.$message.error('保存配置失败');
                    }
                );
            },
            BtsSwitchChange() {
                let isScreen = 0;
                if(this.BtsSwitch){
                    isScreen = 1;
                }

                this.$api.post(
                    '/sceneCfg/updateisScreen',
                    {
                        sceneId: this.sceneId,
                        isScreen: isScreen
                    },
                    res => {
                        
                    },
                    err => {
                        this.$message.error('开启/关闭弹幕失败');
                    }
                );
            }
        }
    };
</script>

<style lang="scss">
    .bulletScreen{
        width: calc(100% - 40px);
        height: calc(100% - 82px);
        padding: 0 20px;
        border-radius: 10px;
        position: relative;
        background-color: #fff;
        margin: 10px auto;
        
        .el-tabs{
            height: 100%;

            .el-tabs__content{
                height: calc(100% - 56px);

                .el-tab-pane{
                    width: 100%;
                    height: 100%;

                    iframe{
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }
        .el-row{
            margin-bottom: 10px;

            .el-button.is-round{
                padding: 6px 20px;
            }
            i{
                &.el-icon-circle-plus-outline, &.el-icon-remove-outline{
                    font-size: 24px;
                    color: #1994FA;
                    line-height: 1.5;
                    margin: 0 5px;
                    cursor: pointer;
                }
            }
        }
        #pane-quickLanguage{
            .quickLanguage-list{
                height: calc(100% - 50px);
                overflow: auto;
            }
        }
        #pane-vipManage{
            border: 1px solid #d8d8d8;
            overflow: auto;

            .vipManage-query{
                padding: 5px 10px;
                background-color: #f0f0f0;
                border-bottom: 1px solid #d8d8d8;
                margin-bottom: 0;

                .el-form{
                    .el-form-item{
                        margin-bottom: 0;

                        .el-input{
                            width: 130px;
                        }
                    }
                }
            }
            .vipManage-list{
                text-align: center;

                .vipManage-list-main{
                    position: relative;

                    .chooseBg{
                        width: 100px;
                        height: 40px;
                        padding: 0;
                        background: url('~@/assets/imgs/icon_bts_bg01.svg') no-repeat;
                        background-size: cover;
                        background-position: center center;
                        position: absolute;
                        left: 0;
                        top: 1px;
                        z-index: 10;

                        .el-button--text{
                            width: 50%;
                            height: 100%;
                            padding: 0;
                            border: none;
                            float: left;
                            margin: 0;

                            span{
                                color: #fff;
                                text-decoration: none;
                            }
                        }
                    }
                    .el-table{
                        .el-button--text{
                            span{
                                color: #D93025;
                                text-decoration: underline;
                            }
                        }
                    }
                }
            }
        }
        .dialogVipBox{
            .user-search{
                position: relative;

                .user-search-list{
                    width: calc(100% - 30px);
                    max-height: 130px;
                    padding: 0 10px;
                    background-color: #fff;
                    border: 1px solid #D8D8D8;
                    overflow: auto;
                    position: absolute;
                    left: 15px;
                    top: 32px;

                    .user-search-list-item{
                        line-height: 30px;
                        margin-bottom: 0;

                    }
                }
            }
            .user-addVip{
                height: 300px;
                padding: 20px;
                border: 1px solid #D8D8D8;
                margin-top: 30px;
                overflow: auto;

                .user-addVip-item{
                    line-height: 30px;
                    padding: 0 5px;
                    border: 1px solid #D8DCE6;
                    margin: 20px;
                }
            }
        }
        .saveSetting{
            .el-button{
                padding: 10px 30px;
                float: right;
                position: absolute;
                right: 30px;
                bottom: -40px;
            }
        }
    }
</style>